<!-- 消耗费用 -->
<template>
  <div class="energy_consume">
    <div class="left_tree">
      <div class="content-left">
        <div class="tree-search">
          <px-input v-model="treeSearchVal" placeholder="请输入" :prefix-icon="Search" />
        </div>
        <div class="tree-bar">
          <px-scrollbar>
            <px-tree
              ref="treeRef"
              :data="treeData"
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              highlight-current
              :current-node-key="currentNode"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              @node-click="handleNodeClick"
            >
              <template #default="{ data }">
                <px-tooltip :content="data.label" placement="top" :show-after="showAfter">
                  <span :style="data.disabled ? { cursor: 'not-allowed', userSelect: 'none' } : ''">
                    {{ data.label }}
                  </span>
                </px-tooltip>
              </template>
            </px-tree>
          </px-scrollbar>
        </div>
      </div>
    </div>
    <div class="right_con">
      <div class="top_query">
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: auto; padding-right: 10px">
            <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
              <!-- <px-radio size="small" label="Hourly">小时</px-radio>
              <px-radio size="small" label="Daily">日</px-radio> -->
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 430px">
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Hourly'"
              v-model="dateRange"
              type="datetimerange"
              range-separator="-"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
            <!-- <div v-else-if="queryParams.queryTimeGranularity === 'Yearly'" class="select_year">
              <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
              <span>&nbsp;-&nbsp;</span>
              <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
            </div> -->
            <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
              <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </div>
          </px-form-item>
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form>
      </div>
      <px-form ref="queryTypeRef" :model="queryTypeParams" :inline="true" label-position="left" style="height: 30px; margin: 8px 0">
        <px-form-item label="" prop="dataFormat">
          <px-radio-group v-model="energyType" style="margin-left: 10px" @change="radioClickFn">
            <px-radio v-for="item in radioOptions" :key="item.name" :size="item.size" :label="item.label">{{ item.name }}</px-radio>
          </px-radio-group>
        </px-form-item>
      </px-form>
      <div class="consume_all_cost">
        <tableEcharts
          :key="tablePieKey"
          title="耗能费用排行"
          :width="1000"
          :height="333"
          :tableColumns="tableColumns"
          :radioOptions="radioOptions"
          :dataList="dataList"
          :options="costOptions"
          :energyType="energyType"
          :showClass="showClass"
          :button="'导出'"
          @btn-click="btnClick('table')"
        />
      </div>
      <div class="echarts_btn">
        <linesCharts
          :key="lineChartKey"
          title="耗能费用趋势"
          :width="1000"
          :height="333"
          :radioOptions="checkboxOptions"
          :options="trendOptions"
          :energyType="energyTypeList"
          :button="'导出'"
          @checkbox-click="checkboxClickFn"
          @btn-click="btnClick('line')"
        />
      </div>
    </div>
  </div>
</template>
<script setup>
defineOptions({
  name: "ALL_ENERGY_COST_CONSUMPTION"
});
import { ref, watch, getCurrentInstance, onMounted, nextTick, reactive, toRefs } from "vue";
import yearPicker from "@/views/common/energy/components/yearPicker.vue";
import { Search } from "@px-ui/icons-vue";
import { queryDictData } from "@/api/common";
import { PxMessage } from "px-ui";
import axios from "axios";
import tableEcharts from "./components/tableEcharts.vue";
import linesCharts from "./components/linesCharts.vue";
import {
  // getConsumeCostOverView,
  getConsumeCostOverViewByclass
} from "@/api/energy/consumeCost";
import dayjs from "dayjs";

const tablePieKey = ref(Date.now());
const lineChartKey = ref(Date.now());

const energyType = ref("all");
const energyTypeList = ref(["electricity", "water"]);

const queryTypeParams = ref({});

const radioOptions = ref([
  {
    label: "all",
    name: "总费用",
    size: "small"
  },
  {
    label: "electricity",
    name: "电",
    size: "small"
  },
  {
    label: "water",
    name: "水",
    size: "small"
  },
  {
    label: "ng",
    name: "天然气",
    size: "small"
  },
  {
    label: "steam",
    name: "蒸汽",
    size: "small"
  },
  {
    label: "hot",
    name: "热水",
    size: "small"
  },
  {
    label: "gas",
    name: "大宗气",
    size: "small"
  }
]);

const checkboxOptions = ref(null);

// 耗能列表的合计，正常是后端返回，后端不好整，由前端继续计算
let totalObj = {
  electricityCost: 0,
  gasCost: 0,
  hotCost: 0,
  ngCost: 0,
  steamCost: 0,
  summaryCost: 0,
  system: "合计",
  waterCost: 0
};

const tableColumns = ref([
  {
    label: "系统",
    prop: "system",
    align: "left"
  },
  {
    label: "总费用(万元)",
    prop: "summaryCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["summaryCost"],
    width: "124"
  },
  {
    label: "电(万元)",
    prop: "electricityCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["electricityCost"],
    width: "100"
  },
  {
    label: "水(万元)",
    prop: "waterCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["waterCost"],
    width: "100"
  },
  {
    label: "天然气(万元)",
    prop: "ngCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["ngCost"],
    width: "124"
  },
  {
    label: "蒸汽(万元)",
    prop: "steamCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["steamCost"],
    width: "110"
  },
  {
    label: "热水(万元)",
    prop: "hotCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["hotCost"],
    width: "110"
  },
  {
    label: "大宗气(万元)",
    prop: "gasCost",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["gasCost"],
    width: "124"
  }
]);

const dataList = ref([]);

const tabPosition = ref("厂务侧");
const { proxy } = getCurrentInstance();
// 定义数据
const dateRange = ref([]);

const showClass = ref(false);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref({ startYear: new Date().getFullYear() - 2, endYear: new Date().getFullYear() });
// const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear = (startYear, endYear) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00` || null;
  yearEnd.value = `${endYear}-12-31 23:59:59` || null;
};

const systemList = ref([]);

const state = reactive({
  treeSearchVal: "",
  treeData: [],
  currentNode: "0",
  showAfter: 1000,
  defaultExpandedKeys: []
});
const { treeSearchVal, treeData, currentNode, showAfter, defaultExpandedKeys } = toRefs(state);

const pageData = ref({});
const pageLineData = ref([]);

const costOptions = ref({});

const trendOptions = ref({});

const getName = v => {
  if (v) {
    return radioOptions.value.find(e => e.label === v).name;
  } else {
    return "-";
  }
};

// 排序
const radioClickFn = async v => {
  console.log(v, "vvvvvvvvvvvvvvvvvv");
  const obj = pageData.value;
  let data = [];
  let lineData = {};
  let arr = [];
  lineData = pageData.value;
  energyType.value = v;
  if (lineData.costTrend && lineData.costTrend.axisMeasureDetailDTOS && lineData.costTrend.axisMeasureDetailDTOS.length) {
    // pageLineData.value = getFilterArr(lineData.costTrend.axisMeasureDetailDTOS, v);
    arr = getFilterArr(lineData.costTrend.axisMeasureDetailDTOS, v);
    reFreshTrend(arr);
  }
  if (v !== "all") {
    if (pageData.value.costRatio && pageData.value.costRatio.length) {
      const findObj = pageData.value.costRatio && pageData.value.costRatio.find(el => el.kind === v);
      data =
        findObj &&
        findObj.ratio &&
        findObj.ratio.map(item => {
          return {
            name: item.name || "-",
            value: item.value ? Number(item.value).toFixed(2) : 0
          };
        });
    } else {
      data = [];
    }
    costOptions.value = labelLayoutFn(data);
    tablePieKey.value = Date.now();
  } else {
    data = dataList.value.map(el => {
      return {
        name: el.system || "-",
        value: el.summaryCost ? Number(el.summaryCost).toFixed(2) : 0
      };
    });
    costOptions.value = labelLayoutFn(data);
    tablePieKey.value = Date.now();
  }
  if (obj.costSummaryTable && obj.costSummaryTable.length) {
    // 深拷贝
    const deepAry = JSON.parse(JSON.stringify(obj.costSummaryTable));
    switch (v) {
      case "all":
        dataList.value = deepAry.sort((a, b) => {
          return b.summaryCost - a.summaryCost;
        });
        break;
      case "electricity":
        dataList.value = deepAry.sort((a, b) => {
          return b.electricityCost - a.electricityCost;
        });
        break;
      case "water":
        dataList.value = deepAry.sort((a, b) => {
          return b.waterCost - a.waterCost;
        });
        break;
      case "ng":
        dataList.value = deepAry.sort((a, b) => {
          return b.ngCost - a.ngCost;
        });
        break;
      case "steam":
        dataList.value = deepAry.sort((a, b) => {
          return b.steamCost - a.steamCost;
        });
        break;
      case "hot":
        dataList.value = deepAry.sort((a, b) => {
          return b.hotCost - a.hotCost;
        });
        break;
      case "gas":
        dataList.value = deepAry.sort((a, b) => {
          return b.gasCost - a.gasCost;
        });
        break;
      default:
        dataList.value = deepAry.sort((a, b) => {
          return b.summaryCost - a.summaryCost;
        });
        break;
    }
    // 合计保留两位小数
    Object.keys(totalObj).forEach(i => {
      if (i !== "system") {
        totalObj[i] = Number(totalObj[i]?.toFixed(2));
      }
    });
    // 把最后的合计加上
    dataList.value.push(totalObj);
  } else {
    return;
  }
};

// 排序
const checkboxClickFn = async v => {
  energyTypeList.value = v;
  const data = (pageLineData.value && pageLineData.value.costTrend && pageLineData.value.costTrend.axisMeasureDetailDTOS) || [];
  const arr = getFilterArr(data, energyType.value);
  reFreshTrend(arr);
};

// 刷新趋势图
const reFreshTrend = arr => {
  console.log(arr, "需要展示的数据");
  let seriesArr = [];
  let yaxisArr = [];
  const xData = (arr && arr[0] && arr[0].xaxis) || [];
  if (arr && arr.length > 0) {
    arr.forEach((item, index) => {
      if (energyTypeList.value.indexOf(item.sysName) > -1) {
        item.yaxis.forEach((el, ind) => {
          seriesArr.push({
            name: `${item.sysName}`,
            type: "line",
            // yAxisIndex: index,
            data: el.value
              ? el.value.map(e => {
                  return Number(Number(e ? e : 0).toFixed(2));
                })
              : [],
            emphasis: {
              focus: "series"
            }
          });
          // yaxisArr.push({
          //   type: "value",
          //   position: "left",
          //   name: `${item.name}\n万元`,
          //   alignTicks: true,
          //   offset: index * 80,
          //   axisLine: {
          //     show: true,
          //     lineStyle: {
          //       width: 1
          //     }
          //   }
          // });
        });
      }
    });
    trendOptions.value = labelLayoutFnTrend(xData, seriesArr, yaxisArr);
  } else {
    trendOptions.value = {};
  }
  lineChartKey.value = Date.now();
};

const treeRef = ref();
watch(
  () => state.treeSearchVal,
  val => {
    treeRef.value.filter(val);
  }
);

const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};

// 获取第一个叶子节点
const getFirstLeaf = node => {
  if (node.children.length === 0) {
    return node;
  }
  for (let i = 0; i < node.children.length; i++) {
    const firstLeaf = getFirstLeaf(node.children[i]);
    if (firstLeaf) {
      return firstLeaf;
    }
  }
  return null;
};

// 末级节点添加diabled
const addDisabled = nodes => {
  nodes.forEach(node => {
    if (node.children && node.children.length > 0) {
      addDisabled(node.children);
    } else {
      node.disabled = true;
    }
  });
};

// 点击树节点
const handleNodeClick = (data, node, obj) => {
  if (data.children.length === 0 || data.id === "feishui") {
    return;
  }
  currentNode.value = data.id;
  getPageData();
};

const getFilterArr = (arr, targetName) => {
  console.log(arr, targetName, "过滤");
  if (arr && arr.length) {
    return arr.map(item => {
      return {
        ...item,
        yaxis: item.yaxis.filter(subItem => subItem.name === targetName)
      };
    });
  } else {
    return [];
  }
};

const getPageData = async () => {
  const classIdList = ["fac"];
  let resData = {};

  const param = {
    startDate: queryParams.value.startTime,
    endDate: queryParams.value.endTime,
    sysId: currentNode.value,
    dimension: queryParams.value.queryTimeGranularity.split("")[0]
  };
  const res1 = await getConsumeCostOverViewByclass(param);
  resData = Object.assign({}, res1);
  pageData.value = resData ? resData : {};
  pageLineData.value = resData ? resData : {};
  let lineData = [];
  if (resData.costTrend && resData.costTrend.axisMeasureDetailDTOS && resData.costTrend.axisMeasureDetailDTOS.length) {
    lineData = getFilterArr(resData.costTrend.axisMeasureDetailDTOS, "all");
    reFreshTrend(lineData);
    if (classIdList.includes(currentNode.value)) {
      tableColumns.value[0].label = "科室";
      checkboxOptions.value = resData.costTrend.axisMeasureDetailDTOS.map(e => {
        return {
          label: e.sysName || "-",
          name: e.sysName,
          size: "small"
        };
      });
      showClass.value = true;
    } else {
      tableColumns.value[0].label = "系统";
      checkboxOptions.value = resData.costTrend.axisMeasureDetailDTOS.map(e => {
        return {
          label: e.sysName || "-",
          name: e.sysName,
          size: "small"
        };
      });
      showClass.value = false;
    }
  } else {
    checkboxOptions.value = [];
  }
  if (resData.costSummaryTable && resData.costSummaryTable.length) {
    // 前端拼接合计
    resData?.costSummaryTable.forEach(item => {
      totalObj.electricityCost += item.electricityCost;
      totalObj.gasCost += item.gasCost;
      totalObj.hotCost += item.hotCost;
      totalObj.ngCost += item.ngCost;
      totalObj.steamCost += item.steamCost;
      totalObj.summaryCost += item.summaryCost;
      totalObj.waterCost += item.waterCost;
    });
    dataList.value = resData.costSummaryTable.sort((a, b) => {
      return b.summaryCost - a.summaryCost;
    });
  } else {
    dataList.value = [];
  }
  const data = dataList.value.map(el => {
    return {
      name: el.system || "-",
      value: el.summaryCost ? Number(el.summaryCost).toFixed(2) : null
    };
  });
  radioClickFn("all");
  costOptions.value = labelLayoutFn(data);
  checkboxClickFn(checkboxOptions.value.map(item => item.name));
  tablePieKey.value = Date.now();
  lineChartKey.value = Date.now();
};

const labelLayoutFn = data => {
  const options = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c} ({d}%)`
    },
    grid: {
      top: "20%",
      bottom: "0%"
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      right: "center", // 水平居中
      itemWidth: 20, // 图例标记的图形宽度
      itemHeight: 10, // 图例标记的图形高度
      data: (data && data.map(el => el.name)) || []
    },
    series: [
      {
        name: "耗能费用排行",
        type: "pie",
        labelLine: {
          length: 15
        },
        label: {
          formatter: `{name|{b}}\n{c|{c}}({d|{d}%})`,
          rich: {
            name: {
              fontSize: 12
            },
            c: {
              fontSize: 12
            },
            d: {
              fontSize: 12,
              fontWeight: "bold"
            }
          }
        },
        radius: "50%",
        data: data || [],
        top: "10%",
        height: "90%"
      }
    ]
  };
  return options;
};

const labelLayoutFnTrend = (xData, serisData, yAxis) => {
  const options = {
    tooltip: {
      trigger: "axis"
    },
    legend: {
      type: "scroll", // 设置图例分页类型为滚动
      icon: "rect",
      orient: "horizontal", // 水平排列
      right: "center", // 水平居中
      itemWidth: 20, // 图例标记的图形宽度
      itemHeight: 10, // 图例标记的图形高度
      selected: {},
      data: serisData.map(e => e.name) || []
    },
    grid: {
      left: "3%",
      right: "24px",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: xData || []
    },
    yAxis: {
      type: "value",
      position: "left",
      name: `${getName(energyType.value)}(万元)`,
      alignTicks: true,
      axisLine: {
        show: true,
        lineStyle: {
          width: 1
        }
      }
    },
    series: serisData || []
  };
  return options;
};

const queryParams = ref({
  queryTimeGranularity: "Monthly"
});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  let d = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = val => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Hourly":
      dateRange.value = [`${year}-${month}-${da} 00:00:00`, `${year}-${month}-${da} 23:59:59`];
      break;
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      break;
    case "Yearly":
      let yearS = new Date().getFullYear() - 2;
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

/** 搜索按钮操作 */
function handleQuery() {
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Hourly") {
    //获取新的时间
    let date = new Date();
    //获取当前时间的年份转为字符串
    let year = date.getFullYear().toString();
    //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
    let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
    //获取天，判断是否小于10，如果是在字符串前面拼接'0'
    let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  getPageData();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

const initQuery = () => {
  // queryParams.value.queryTimeGranularity = "Monthly";
  // dateRange.value = [dayjs().subtract(12, "month").format("YYYY-MM"), dayjs().subtract(1, "month").format("YYYY-MM")];
  // const startDate = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
  // const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
  // const endDate = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  // queryParams.value.startTime = startDate;
  // queryParams.value.endTime = endDate;
  // getPageData();
  queryParams.value.queryTimeGranularity = "Monthly";
  dateRange.value = [dayjs().subtract(12, "month").format("YYYY-MM"), dayjs().subtract(1, "month").format("YYYY-MM")];
  queryParams.value.startTime = dayjs().subtract(12, "month").format("YYYY-MM") + "-01 00:00:00";
  queryParams.value.endTime = dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD") + " 23:59:59";
  getPageData();
};

const getTreeData = async () => {
  // 获取树节点数据
  let url = "";
  if (tabPosition.value === "厂务侧") {
    url = "/models/treeData.json";
  } else if (tabPosition.value === "机台侧") {
    url = "/models/equip.json";
  } else {
    url = "/models/others.json";
  }
  const jsonData = await axios.get(url);
  treeData.value = jsonData.data.data;
  addDisabled(treeData.value);
  nextTick(() => {
    currentNode.value = treeData.value[0]?.id;
    treeRef.value.setCurrentKey([treeData.value[0]?.id]);
    initQuery();
  });
};

const getData = (url, tag) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url)
      .then(res => {
        let data = res.data.data;
        let resData = [];
        let tagTitle = tag;
        // 给节点打标记
        resData = data.map(node => {
          return addPropertyToLeafNodes(node, tagTitle);
        });
        resolve(resData[0]);
      })
      .catch(error => {
        reject(error);
      });
  });
};

// 递归函数，用于给叶子节点添加属性
const addPropertyToLeafNodes = (node, args) => {
  if (!node.children || node.children.length === 0) {
    // 是叶子节点，添加属性
    node.disabled = true;
    node.flag = args;
  } else {
    node.flag = args;
    // 不是叶子节点，递归遍历子节点
    node.children.forEach(child => {
      addPropertyToLeafNodes(child, args);
    });
  }
  return node;
};

// 拼接数据
const getAllTreeData = async () => {
  const url1 = "/models/treeData.json";
  const url2 = "/models/equip.json";
  const url3 = "/models/others.json";
  const res = await Promise.all([getData(url1, "fac"), getData(url2, "equip"), getData(url3, "other")]);
  let resAry = [
    {
      id: "全厂",
      label: "全厂",
      flag: "quanchang",
      disabled: false,
      children: [...res]
    }
  ];
  state.treeData = resAry;
  state.defaultExpandedKeys = collectGrandparentKeys(resAry);
  nextTick(() => {
    state.currentNode = resAry[0].children[0].id;
    treeRef.value.setCurrentKey([resAry[0].children[0].id]);
  });
};

const collectGrandparentKeys = data => {
  const stack = data.map(node => ({
    node,
    parentId: null,
    grandparentId: null
  }));
  const result = new Set();

  while (stack.length > 0) {
    const { node, parentId, grandparentId } = stack.pop();

    if (Array.isArray(node.children) && node.children.length === 0) {
      if (grandparentId !== null) result.add(grandparentId);
    } else if (Array.isArray(node.children) && node.children.length > 0) {
      // 将子节点压入栈，并传递当前节点的父级和祖父级信息
      node.children.forEach(child => {
        stack.push({
          node: child,
          parentId: node.id,
          grandparentId: parentId
        });
      });
    }
  }

  return Array.from(result);
};

const btnClick = val => {
  let params = pageData.value;
  params.type = val;
  params.label = energyType.value || "";
  if (val === "table") {
    proxy.download("post", "/energy/energyCost/exportMeasurement", params, "消耗成本-耗能费用排行.xlsx");
  } else {
    proxy.download("post", "/energy/energyCost/exportMeasurement", params, "供给费用-耗能费用趋势.xlsx");
  }
};

onMounted(async () => {
  // getTreeData();
  getAllTreeData();
  initQuery();
  systemList.value = await queryDictData({ typeCode: "factoryArea" });
});
</script>

<style lang="scss" scoped>
.energy_consume {
  display: flex;

  .left_tree {
    width: 310px;
    padding: 16px 24px;
    margin-right: 16px;
    background-color: #fff;
    border-radius: 4px;

    /*
    * tab样式
    */
    .tabSwitch {
      padding: 4px;
      background-color: #f4f4f4;
      border-radius: 4px;

      :deep(.px-radio-button__inner) {
        background-color: #f4f4f4;
        border: none;
      }

      :deep(.is-active) {
        border: none;

        .px-radio-button__inner {
          background-color: var(--px-color-primary);
          border-radius: 4px;
        }
      }
    }

    .content-left {
      .tree-title {
        padding: 8px 8px 0;
        font-size: 14px;
        font-weight: bold;
      }

      .tree-search {
        padding: 8px;
      }

      .tree-bar {
        width: 100%;
        height: calc(100vh - 250px);
        overflow-y: auto;
      }
    }
  }

  .right_con {
    display: flex;
    flex: 1;
    flex-flow: column;
    width: calc(100% - 326px);
    // gap: 16px;

    .top_query {
      display: flex;
      flex-flow: row nowrap;
      min-width: 1000px;
      height: 76px;
      padding: 16px 24px;
      background: #fff;
      border-radius: 4px;
    }

    .select_year {
      display: flex;
      align-items: center;
      justify-content: left;
      margin-right: 20px;
    }

    .px-form-item {
      margin-bottom: 0;
    }

    .consume_all_cost {
      width: 100%;
      min-width: 1000px;
      height: 314px;
    }

    .echarts_btn {
      width: 100%;
      min-width: 1000px;
      height: 340px;
      margin-top: 16px;
    }
  }
}
</style>
